package com.yihuier.yihuier.Controller.MeetingManager;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihuier.yihuier.Controller.Common.FileController;
import com.yihuier.yihuier.Controller.Common.TimeJudgeController;
import com.yihuier.yihuier.Controller.UserManager.UserController;
import com.yihuier.yihuier.Entity.MeetingManager.*;
import com.yihuier.yihuier.Entity.MeetingManager.DTO.*;
import com.yihuier.yihuier.Entity.MeetingManager.DTO.MeetingDTO;
import com.yihuier.yihuier.Entity.RoomManager.Room;
import com.yihuier.yihuier.Entity.UserManager.User;
import com.yihuier.yihuier.Service.Common.FileUploadService;
import com.yihuier.yihuier.Service.Common.ServiceCheckService;
import com.yihuier.yihuier.Service.MeetingManager.*;
import com.yihuier.yihuier.Service.RoomManager.RoomService;
import com.yihuier.yihuier.Service.UserManager.DepartmentService;
import com.yihuier.yihuier.Service.UserManager.DepartmentUserService;
import com.yihuier.yihuier.Service.UserManager.UserService;
import com.yihuier.yihuier.Util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.nio.file.Path;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/MeetingManager/Meetings/")
public class MeetingController {

    @Autowired
    MeetingService meetingService;

    @Autowired
    UserService userService;

    @Autowired
    RoomService roomService;

    @Autowired
    MeetingUserService meetingUserService;

    @Autowired
    MeetingRoomService meetingRoomService;

    @Autowired
    ServiceCheckService serviceCheckService;

    @Autowired
    MeetingCollectionService meetingCollectionService;

    @Autowired
    MeetingApplyService meetingApplyService;

    @Autowired
    MeetingDataService meetingDataService;

    @Autowired
    MeetingAttendService meetingAttendService;

    @Autowired
    DepartmentUserService departmentUserService;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    FileUploadService fileUploadService;

    @Autowired
    UserController userController;

    @Autowired
    TimeJudgeController timeJudgeController;

    @Value("${yihuier.QrCode.disposit}")
    private Path QrCode_Path;


    @GetMapping("latestMeetings")
    public ResponseMessage getLatestMeetings(@RequestParam(value = "offset", defaultValue = "-1") int offset, @RequestParam(value = "rows", defaultValue = "-1") int rows) {
        List<Meeting> results = meetingService.getLatestMeetings(offset, rows);
        if (results != null) {
            return new ResponseMessage(ResponseMessage.SUCCESS, "获取成功", results);
        } else {
            return new ResponseMessage(ResponseMessage.ERROR, "数据库错误");
        }
    }

    @PostMapping("meetingUsers.json")
    public ResponseMessage getMeetingUsers(@PathParam("meeting_id") int meeting_id, HttpServletRequest request) {
        timeJudgeController.updateMeetingAndPersonStatus(meeting_id);//更新会议状态
        List<Integer> userIdList = meetingUserService.getMeetingUserIds(meeting_id);//参会用户id数组
        ArrayList<Map<Object, Object>> MeetingUsers = new ArrayList<Map<Object, Object>>();
        for (int userid : userIdList) {
            HashMap<Object, Object> mapUser = new HashMap<Object, Object>();
            User user = userService.getUserinfomationByUserid(userid);
            mapUser.put("user_id", user.getUser_id());
            mapUser.put("user_name", user.getUser_name());
            mapUser.put("user_headpic_dir", FileController.filePathDispose(user.getUser_headpic_dir()));
            mapUser.put("user_email", user.getUser_email());
            MeetingUsers.add(mapUser);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户数据获取成功", MeetingUsers);
    }

    @PostMapping("personalApplyMeetings.json")
    public ResponseMessage getPersonalApplyMeetings(@PathParam("user_id") int user_id, HttpServletRequest request) {
        List<MeetingApply> personalApplyMeetings = meetingApplyService.getPersonalApplyMeetings(user_id);
        ArrayList<Map<Object, Object>> personalApplyMeetingsData = new ArrayList<Map<Object, Object>>();
        for (MeetingApply MeetingObj : personalApplyMeetings) {
            LinkedHashMap<Object, Object> meetingInfo = new LinkedHashMap<Object, Object>();
            meetingInfo.put("meeting_id_apply",MeetingObj.getApp_meeting_id());
            meetingInfo.put("meetingName", MeetingObj.getApp_name());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (MeetingObj.getMeeting_time() == null){//会议时间有可能为空
                meetingInfo.put("startTime", "");
            }else {
                meetingInfo.put("startTime", sdf.format(MeetingObj.getMeeting_time()));
            }
            meetingInfo.put("during_time", MeetingObj.getDuring_time());
            String allocationWay;
            if (MeetingObj.getIsIntelligence_allocation() == 0) {
                allocationWay = "人工分配";
            } else {
                allocationWay = "智能分配";
            }
            meetingInfo.put("allocationWay", allocationWay);
            String[] hardware = MeetingObj.getHardware_applicant().split(",");
            meetingInfo.put("hardware", hardware);
            String[] people = userService.getUserNamesByUserIds(MeetingObj.getEm_list().split(","));
            meetingInfo.put("people", people);
            meetingInfo.put("scribe", MeetingObj.getApp_description());
            if (MeetingObj.getLocation() == null){//申请时未申请会议室
                meetingInfo.put("location", "未分配");
                meetingInfo.put("location_pic","http://39.108.10.155:80/file/meeting_room_pic/daifenpei.png");
            }else {
                String roomName = roomService.getRoomNameByRoomId(MeetingObj.getLocation());
                meetingInfo.put("location", roomName);
                String room_pic_url = roomService.getRoomPicByRoomId(MeetingObj.getLocation());
                meetingInfo.put("location_pic", FileController.filePathDispose(room_pic_url));
            }
            meetingInfo.put("remarks", MeetingObj.getOther());
            personalApplyMeetingsData.add(meetingInfo);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户数据获取成功", personalApplyMeetingsData);
    }

    /**
     * 获取用户即将参加的两次会议的信息
     * */
    @PostMapping("LatestMeetingInfomation.json")
    public ResponseMessage getLatestTwoMeetingInfomation(@PathParam("user_id") int user_id, HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设定时间格式规范
        ArrayList<Map<String,Object>> twoData = meetingService.getLatestTwoMeetingInfomation(user_id);
        int i = 0;
        for (Map<String,Object> littleData: twoData) {
            int s =timeJudgeController.updateMeetingAndPersonStatus(Integer.parseInt(""+littleData.get("meeting_id")));//更新会议状态
            //修改会议室名称
            String room_name = roomService.getRoomNameByRoomId((Long) twoData.get(i).get("location"));
            twoData.get(i).put("location",room_name);
            //设定时间格式规范
            twoData.get(i).put("meeting_time_start",sdf.format(twoData.get(i).get("meeting_time_start")));
            //设置会议状态
            if ((Integer)littleData.get("meeting_status") == 0){
                twoData.get(i).put("meeting_status","未开始");
            }else if ((Integer)littleData.get("meeting_status") == 1){
                twoData.get(i).put("meeting_status","即将开始");
            }else if ((Integer)littleData.get("meeting_status") == 2){
                twoData.get(i).put("meeting_status","正在开会");
            }
            String QrCode = "http://39.108.10.155:80/file/meeting_room_QrCode/01.jpg";//默认二维码图片
            if (fileUploadService.findFileIsExist(QrCode_Path,"0"+twoData.get(i).get("meeting_id")+".jpg")){
                QrCode = "http://39.108.10.155:80/file/meeting_room_QrCode/0"+twoData.get(i).get("meeting_id")+".jpg";
            }
            twoData.get(i).put("QrCode",QrCode);
            ++i;
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户即将参加的最近两场会议",twoData);
    }

    /**
     * 获取用户即将参加的所有会议的信息
     * */
    @PostMapping("allMeetingInfomation.json")
    public ResponseMessage getMeetingInfomation(@PathParam("user_id") int user_id, HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设定时间格式规范
        ArrayList<Map<String,Object>> allData = meetingService.getAllMeetingInfomation(user_id);
        int i = 0;
        for (Map<String,Object> littleData: allData) {
            timeJudgeController.updateMeetingAndPersonStatus(Integer.parseInt(""+littleData.get("meeting_id")));//更新会议状态
            //修改会议室名称
            String room_name = roomService.getRoomNameByRoomId((Long) allData.get(i).get("location"));
            allData.get(i).put("location",room_name);
            //设定时间格式规范
            allData.get(i).put("meeting_time_start",sdf.format(allData.get(i).get("meeting_time_start")));
            //设置会议状态
            if ((Integer)littleData.get("meeting_status") == 0){
                allData.get(i).put("meeting_status","未开始");
            }else if ((Integer)littleData.get("meeting_status") == 1){
                allData.get(i).put("meeting_status","即将开始");
            }else if ((Integer)littleData.get("meeting_status") == 2){
                allData.get(i).put("meeting_status","正在开会");
            }
            String QrCode = "http://39.108.10.155:80/file/meeting_room_QrCode/01.jpg";//默认二维码图片
            if (fileUploadService.findFileIsExist(QrCode_Path,"0"+allData.get(i).get("meeting_id")+".jpg")){
                QrCode = "http://39.108.10.155:80/file/meeting_room_QrCode/0"+allData.get(i).get("meeting_id")+".jpg";
            }
            allData.get(i).put("QrCode",QrCode);
            ++i;
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户即将参加的最近两场会议",allData);
    }

    @PostMapping("collectionMeetings.json")
    public ResponseMessage getcollectionMeetings(@PathParam("user_id")int user_id){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<MeetingCollection> collectionMeetingIdAndTime= meetingCollectionService.getCollectionMeetingIdAndTime(user_id);
        if (collectionMeetingIdAndTime.size() == 0){
            return new ResponseMessage(ResponseMessage.ERROR, "用户没有收藏会议");
        }
        ArrayList<Map<String,Object>> collectionMeetingData = new ArrayList<Map<String,Object>>();
        for (MeetingCollection littleMeetingCollection:collectionMeetingIdAndTime) {
            timeJudgeController.updateMeetingAndPersonStatus(Integer.parseInt(""+littleMeetingCollection.getMeeting_id()));//更新会议状态
            LinkedHashMap<String,Object> Data = new LinkedHashMap<String,Object>();
            Data.put("meeting_id",littleMeetingCollection.getMeeting_id());
            Data.put("collection_time",sdf.format(littleMeetingCollection.getCollection_time()));
            Map<String,Object> littleMeetingInfo = meetingService.getCollectionMeetingInfoByMeetingId(littleMeetingCollection.getMeeting_id());
            Data.put("meeting_status",littleMeetingInfo.get("meeting_status"));
            Data.put("meeting_name",littleMeetingInfo.get("meeting_name"));
            Data.put("description",littleMeetingInfo.get("description"));
            Map<String,Object> littleMeetingTimes =  meetingRoomService.getMeetingTimes((Long)littleMeetingInfo.get("location"),littleMeetingCollection.getMeeting_id());
            if (littleMeetingTimes == null){
                Data.put("startTime","测试会议，时间未知");
                Data.put("duringTime","测试会议，时间未知");
            }else{
                Data.put("startTime",sdf.format(littleMeetingTimes.get("meeting_time_start")));
                Data.put("duringTime",littleMeetingTimes.get("meeting_time"));
            }
            String roomName = roomService.getRoomNameByRoomId((Long)littleMeetingInfo.get("location"));
            Data.put("location",roomName);
            int[] attendUsersIds = meetingUserService.gettAttendUsersIds(littleMeetingCollection.getMeeting_id());
            List<Map<String,Object>> userInfo = userService.getUsersByUserIds(attendUsersIds);
            for (int i=0;i<userInfo.size();i++) {
                userInfo.get(i).put("user_headpic_dir",FileController.filePathDispose((String)userInfo.get(i).get("user_headpic_dir")));
            }
            Data.put("people",userInfo);
            collectionMeetingData.add(Data);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "用户收藏会议信息获取成功", collectionMeetingData);
    }

    @PostMapping("MeetingFiles.json")
    public ResponseMessage getMeetingFileData(@PathParam("meeting_id") int meeting_id, HttpServletRequest request){
        timeJudgeController.updateMeetingAndPersonStatus(meeting_id);//更新会议状态
        List<MeetingData> meetingData = meetingDataService.getMeetingFileData(meeting_id);
        ArrayList<Map<String,Object>> meetingFiles = new ArrayList<Map<String,Object>>();
        for (MeetingData littleData: meetingData) {
            LinkedHashMap<String,Object>  littleFile = new LinkedHashMap<String,Object>();
            littleFile.put("data_id",littleData.getData_id());
            littleFile.put("meeting_id",littleData.getData_meeting_id());
            littleFile.put("file_name",littleData.getData_name());
            littleFile.put("data_address",FileController.filePathDispose(littleData.getData_address()));
            meetingFiles.add(littleFile);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS, "隶属于会议的文件",meetingFiles);
    }

    /**
     * 获取与我有关的的会议
     * */
    @PostMapping("relateToMeMeetings.json")
    public ResponseMessage getRelateToMeMeetings(@PathParam("user_id") int user_id){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设定时间格式规范
        ArrayList<Map<String,Object>> Data = meetingService.getRelatedToMeMeetingInfomation(user_id);
        ArrayList<Map<String,Object>> RelateToMeMeetingsData = new ArrayList<Map<String,Object>>();
        for (Map<String,Object> littleData:Data){
            timeJudgeController.updateMeetingAndPersonStatus(Integer.parseInt(""+littleData.get("meeting_id")));//更新会议状态
            LinkedHashMap<String,Object> littleMap = new LinkedHashMap<String,Object>();
            littleMap.put("meeting_id",littleData.get("meeting_id"));
            littleMap.put("meeting_colletion_status",meetingCollectionService.getCollectionStatusByUserIdAndMeetingId(user_id,(Long)littleData.get("meeting_id")));
            littleMap.put("meeting_name",littleData.get("meeting_name"));
            littleMap.put("description",littleData.get("description"));
            littleMap.put("startTime",sdf.format(littleData.get("meeting_time_start")));
            littleMap.put("meeting_time",littleData.get("meeting_time"));//会议持续时间
            String room_name = roomService.getRoomNameByRoomId((Long) littleData.get("location"));
            littleMap.put("location",room_name);//地点名
            String room_pic = roomService.getRoomPicByRoomId((Number)littleData.get("location"));
            littleMap.put("location_pic",room_pic);//会议室照片
            if ((Integer)littleData.get("meeting_status") == 0){
                littleMap.put("meeting_status","未开始");//会议状态
            }else if ((Integer)littleData.get("meeting_status") == 1){
                littleMap.put("meeting_status","即将开始");//会议状态
            }else if ((Integer)littleData.get("meeting_status") == 2){
                littleMap.put("meeting_status","正在开会");//会议状态
            }else if ((Integer)littleData.get("meeting_status") == 3){
                littleMap.put("meeting_status","已结束");//会议状态
            }
            String attend_attendence = meetingAttendService.getAttend_attendence(user_id,(Long)littleData.get("meeting_id"));
            if (attend_attendence == null){
                littleMap.put("attendence_status","未知");//到达状态
            }else {
                if (attend_attendence.equals("0")){
                    littleMap.put("attendence_status","准时到达");//到达状态
                }else if (attend_attendence.equals("1")){
                    littleMap.put("attendence_status","迟到");//到达状态
                }else if (attend_attendence.equals("2")){
                    littleMap.put("attendence_status","请假");//到达状态
                }else if (attend_attendence.equals("3")){
                    littleMap.put("attendence_status","缺勤");//到达状态
                } else if (attend_attendence.equals("4")){
                    littleMap.put("attendence_status","未到");//到达状态
                }
            }
            int[] attendUsersIds = meetingUserService.gettAttendUsersIds((Long)littleData.get("meeting_id"));
            List<Map<String,Object>> userInfo = userService.getUsersByUserIds(attendUsersIds);
            littleMap.put("users",userInfo);
            RelateToMeMeetingsData.add(littleMap);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS,"获取与我有关的，我要参加的会议",RelateToMeMeetingsData);
    }

    @PostMapping("searchRoomsOrMeetings.json")
    public ResponseMessage searchRoomsOrMeetings(@PathParam("content")String content,@PathParam("user_id")int user_id){
        int department_id = departmentUserService.getDepartmentIdByUserId(user_id);
        int company_id = departmentService.getCompanyIdByDepartmentId(department_id);
        ArrayList<LinkedHashMap<String,Object>> data = new ArrayList<LinkedHashMap<String,Object>>();
        List<Map<String,Object>> vagueRooms = roomService.getRoomIdAndRoomNameByVague(content,company_id);
        for (int i=0;i<vagueRooms.size();i++){
            LinkedHashMap<String,Object> littleData = new LinkedHashMap<>();
            littleData.put("id",vagueRooms.get(i).get("room_id"));
            littleData.put("name",vagueRooms.get(i).get("room_name"));
            littleData.put("type",1);
            data.add(littleData);
        }
        ArrayList<Map<String,Object>> vagueMeetings = meetingService.getRelatedToMeMeetingIdAndMeetingNameByVague(content,user_id);
        for (int i=0;i<vagueMeetings.size();i++){
            int tag = timeJudgeController.updateMeetingAndPersonStatus(Integer.parseInt(""+vagueMeetings.get(i).get("meeting_id")));//更新会议状态
            LinkedHashMap<String,Object> littleData = new LinkedHashMap<>();
            littleData.put("id",vagueMeetings.get(i).get("meeting_id"));
            littleData.put("name",vagueMeetings.get(i).get("meeting_name"));
            littleData.put("type",2);
            littleData.put("tag",tag);
            data.add(littleData);
        }
        return new ResponseMessage(ResponseMessage.SUCCESS,"模糊搜索成功",data);
    }

    /**
     *@param bookMeetingDTO 接受数据集
     * @return 会议预定结果
     */
    @PostMapping("bookMeeting.do")
    public ResponseMessage bookMeeting(
            @RequestBody BookMeetingDTO bookMeetingDTO){
        //检查公司服务是否到期

        System.out.println(bookMeetingDTO);
        if (!serviceCheckService.isUserOfCompanyServiceValid(bookMeetingDTO.getUser_id())){
            //服务到期，不支持预定
            return new ResponseMessage(ResponseMessage.ERROR,"您所在公司服务到期，请续费");
        }

        String em_list = changeListToString(bookMeetingDTO.getPeople());
        String gear = changeListToString(bookMeetingDTO.getHardware());
        //先插入到申请表中
        int meeting_apply_id = this.meetingService.addOneBasicMeetingApply(bookMeetingDTO.getMeetingName(),glueTwoStringToDate(bookMeetingDTO.getStartDay(), bookMeetingDTO.getStartTime()), bookMeetingDTO.getLastTime(), bookMeetingDTO.getRoom_id(), bookMeetingDTO.getPeople().size(),em_list,3, bookMeetingDTO.getUser_id(),gear, bookMeetingDTO.getIsIntellgence(), bookMeetingDTO.getOther(), bookMeetingDTO.getDescription());

        switch (bookMeetingDTO.getIsIntellgence()){
            case 0:
                //智能分配关闭
                return new ResponseMessage(ResponseMessage.SUCCESS,"预定成功，等待管理员审核");
            case 1:
                //智能分配开启
                //attend和meeting_user两个表
                Timestamp meeting_time = glueTwoStringToDate(bookMeetingDTO.getStartDay(), bookMeetingDTO.getStartTime());
                Room room = meetingService.bookOneMeeting(bookMeetingDTO.getUser_id(), bookMeetingDTO.getRoom_id(),meeting_time, bookMeetingDTO.getLastTime(), bookMeetingDTO.getHardware(), bookMeetingDTO.getPeople(), bookMeetingDTO.getOther(), bookMeetingDTO.getMeetingName(),meeting_apply_id, bookMeetingDTO.getDescription());
                if (room == null){
                    return new ResponseMessage(ResponseMessage.ERROR,"申请失败，没有符合条件的会议室");
                }else {
                    HashMap<String,Room> result = new HashMap<>();
                    result.put("room",room);
                    return new ResponseMessage(ResponseMessage.SUCCESS,"申请成功",result);
                }
            default:
                return new ResponseMessage(ResponseMessage.ERROR,"智能请求失败");
        }
    }

    @PostMapping("usersRelateMeetings.json")
    public ResponseMessage getUsersRelateMeetings(@RequestParam("userId")String strUserid){
        int userid = Integer.parseInt(strUserid);
        int [] meetingsOfUserHave = this.meetingUserService.getMeetingOfUserHave(userid);
        int appointmentMeeting = this.meetingApplyService.getNumOfMeetingApplyByUser(userid);
        int closedMeeting = this.meetingService.getNumOfClosedMeetingByUser(meetingsOfUserHave);
        int readyMeeting = this.meetingService.getNumOfReadyMeetingByUser(meetingsOfUserHave);
        int invalidMeeting = this.meetingService.getNumOfInvalidMeetingByUser(meetingsOfUserHave);
        HashMap<String,Integer> resultdata = new HashMap<>();
        resultdata.put("appointment",appointmentMeeting);
        resultdata.put("closed",closedMeeting);
        resultdata.put("ready",readyMeeting);
        resultdata.put("invalid",invalidMeeting);
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",resultdata);
    }


    private Timestamp glueTwoStringToDate(String startDay,String startTime){
        if (startDay == null || startTime == null){
            return null;
        }
        if (startDay.equals("") || startTime.equals("")){
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp result = null;
        try {
            result = new Timestamp(formatter.parse(startDay + " " + startTime + ":00").getTime());

        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("解析出错");
        }
        return result;
    }

    /**
     * 将List中数据一个个取出来拼接成字符串，以“,”分割
     * @param items 数据
     * @return 拼接后的字符串
     */
    private String changeListToString(List items) {
        if (items.size() == 0){
            return "";
        }
        StringBuilder builder = new StringBuilder();
        builder.append(items.get(0));
        for (int i = 1 ; i < items.size() ; i ++){
            builder.append(",").append(items.get(i));
        }
        return builder.toString();
    }

    /**
     * 用户申请加入某会议
     * */
    @PostMapping("ApplyToAttentMeeting.do")
    public ResponseMessage userApplyToAttentMeeting(@PathParam("user_id")int user_id,@PathParam("meeting_id")int meeting_id){
        timeJudgeController.updateMeetingAndPersonStatus(meeting_id);//更新会议状态
        int applyResult = meetingUserService.insertUserApplyToAttendMeeting(user_id,meeting_id);
        if (applyResult == 1){
            return new ResponseMessage(ResponseMessage.SUCCESS,"申请成功");
        }
        return new ResponseMessage(ResponseMessage.ERROR,"数据库错误");
    }

    @GetMapping("userRelatedReadyMeeting.json")
    public ResponseMessage userRelatedReadyMeeting(@PathParam("user_id")int user_id){
        int [] meetingsOfUserHave = this.meetingUserService.getMeetingOfUserHave(user_id);
        List<MeetingDTO> result = this.meetingService.getReadyMeetingByUser(meetingsOfUserHave);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < result.size() ;i++){
            MeetingDTO temp = result.get(i);
            temp.setStrStartTime(sdf.format(temp.getStartTime()));
            temp.setPic_url(FileController.filePathDispose(temp.getPic_url()));
        }
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",result);
    }

    @GetMapping("getRoomNameById.json")
    public ResponseMessage getRoomNameById(@PathParam("location")Long location){
        String roomName = roomService.getRoomNameByRoomId(location);
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",roomName);
    }

    @GetMapping("userRelatedClosedMeeting.json")
    public ResponseMessage userRelatedClosedMeeting(@PathParam("user_id")int user_id){
        int [] meetingsOfUserHave = this.meetingUserService.getMeetingOfUserHave(user_id);
        List<MeetingDTO> result = this.meetingService.getClosedMeetingByUser(meetingsOfUserHave);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < result.size() ;i++){
            MeetingDTO temp = result.get(i);
            temp.setStrStartTime(sdf.format(temp.getStartTime()));
            temp.setPic_url(FileController.filePathDispose(temp.getPic_url()));
        }
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",result);
    }
    @GetMapping("userRelatedInvalidMeeting.json")
    public ResponseMessage userRelatedInvalidMeeting(@PathParam("user_id")int user_id){
        int [] meetingsOfUserHave = this.meetingUserService.getMeetingOfUserHave(user_id);
        List<MeetingDTO> result = this.meetingService.getInvalidMeetingByUser(meetingsOfUserHave);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < result.size() ;i++){
            MeetingDTO temp = result.get(i);
            temp.setStrStartTime(sdf.format(temp.getStartTime()));
            temp.setPic_url(FileController.filePathDispose(temp.getPic_url()));
        }
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",result);
    }

    @GetMapping("meetingApplyInfos.json")
    public ResponseMessage meetingApplyInfo(@PathParam("status")int status,HttpServletRequest request){
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int user_id = Integer.parseInt(manager_id);
        List<MeetingApplyInfoDTO> result = this.meetingService.getMeetingApplyByStatus(status,user_id);
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",result);
    }

    @PostMapping("auditMeetingApply.do")
    public ResponseMessage auditMeetingApply(@RequestBody MeetingApplyDTO meetingApplyDTO,HttpServletRequest request){
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        int user_id = Integer.parseInt(manager_id);
        System.out.println(meetingApplyDTO);
        System.out.println(user_id);
        // 更新会议申请
        this.meetingApplyService.updateMeetingApply(meetingApplyDTO);

        if (this.meetingService.auditMeetingApply(meetingApplyDTO,user_id)){
            return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功");
        }else {
            return new ResponseMessage(ResponseMessage.ERROR, "请求失败");
        }
    }

    /**
     *
     * @param jsonData 用户id：int user_id，参会人数：int em_num，硬件要求：String [] hardware
     * @return
     * @throws IOException
     */
    @PostMapping("gearAndSizeFitRoom.json")
    public ResponseMessage getGearAndSizeFitRoom(@RequestBody String jsonData,HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        String manager_id = (String) session.getAttribute("manager_id");
        if (manager_id == null) {
            return new ResponseMessage(ResponseMessage.ERROR, "管理员账户登陆超时");
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(jsonData);
        JsonNode hardwareJSON = node.get("hardware");
        List<String> hardwareTemp = new ArrayList<>();
        for (JsonNode temp : hardwareJSON){
            hardwareTemp.add(temp.asText());
        }
        String [] hardware = new String[hardwareTemp.size()];
        hardwareTemp.toArray(hardware);
//        List<Room> rooms = this.roomService.getFitRoom(node.get("user_id").asInt(),node.get("em_num").asInt(),hardware);
        List<Room> rooms = this.roomService.getFitRoom(Integer.parseInt(manager_id),node.get("em_num").asInt(),hardware);
        for (Room room : rooms){
            room.setRoom_pic_url(FileController.filePathDispose(room.getRoom_pic_url()));
        }
        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",rooms);
    }

    /**
     *
     * @param jsonData room_time_request:{room_id,startDay}
     * @return
     * @throws IOException
     */
    @PostMapping("roomUsingStatus.json")
    public ResponseMessage getRoomUsingStatus(@RequestBody String jsonData) throws IOException, ParseException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(jsonData);
        JsonNode temp = node.get("room_time_request");

        System.out.println(jsonData);

        List<RoomTimeDTO> roomTimeDTOS = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");

        for (JsonNode tempNode : temp){
            RoomTimeDTO request = new RoomTimeDTO();
            request.setRoom_id(tempNode.get("room_id").asInt());
            request.setStartDay(sdf.parse(tempNode.get("startDay").asText()));
            roomTimeDTOS.add(request);
        }

        this.meetingRoomService.checkAvailble(roomTimeDTOS);

        return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",roomTimeDTOS);
    }

    @PostMapping("userAttendReason.do/{user_id}/{meeting_id}/{reason}")
    public ResponseMessage updateUserAttendReson(@PathVariable("user_id")int user_id,@PathVariable("meeting_id")int meeting_id,@PathVariable("reason")String reason){
        if (this.meetingAttendService.updateUserAttendReson(user_id,meeting_id,reason)) {
            return  new ResponseMessage(ResponseMessage.SUCCESS,"请求成功");
        }
        return new ResponseMessage(ResponseMessage.ERROR,"请求失败");
    }
    @PostMapping("auditUserWantToJoinMeetingRequest.do/{user_id}/{meeting_id}/{status}")
    public ResponseMessage auditUserWantToJoinMeetingRequest(@PathVariable("user_id")int user_id,@PathVariable("meeting_id")int meeting_id,@PathVariable("status")int status,HttpServletRequest request){
        Integer manager_id = (Integer) request.getSession().getAttribute("manager_id");
        if (manager_id == null){
            manager_id = 1;
        }
        if (this.meetingUserService.auditUserJoinRequest(manager_id,user_id,meeting_id,status)){
            return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功");
        }else {
            return new ResponseMessage(ResponseMessage.ERROR,"请求失败");
        }
    }

    @PostMapping("employAttendStatus.json")
    public ResponseMessage getEmployAttendStatus(@RequestBody int[] user_ids){
        List<UserAttendenceDTO> userAttendenceDTOS = this.meetingAttendService.getUserMeetingStatistics(user_ids);
        if ( userAttendenceDTOS != null){
            return new ResponseMessage(ResponseMessage.SUCCESS,"请求成功",userAttendenceDTOS);
        }else {
            return new ResponseMessage(ResponseMessage.ERROR,"请求失败");
        }
    }


}
